<template>
  <!-- 商品管理-商品管理 -->
  <div class="CommodityManagement">
    <el-card class="box-card CommodityManagement_header">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="商品搜索：">
          <el-input v-model="skuName" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            class="btn_search"
            @click="onSubmit"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card CommodityManagement_header">
      <!-- 新建区域 -->
      <el-row>
        <el-col
          :span="2"
        ><div class="grid-content bg-purple-dark">
          <el-button
            type="primary"
            icon="el-icon-circle-plus-outline"
            class="com_newFile"
            @click="openDialog('add')"
          >新建</el-button>
        </div></el-col>
        <!-- 导入数据区域 -->
        <el-col
          :span="8"
        ><div class="grid-content bg-purple-dark">
          <el-button
            type="primary"
            class="com_importData"
            @click="importData"
          >导入数据</el-button>
        </div></el-col>
      </el-row>

      <!-- 表格区域 -->
      <div class="com_table">
        <!-- background-color:#f3f6fb -->
        <el-table
          :data="tableData"
          style="width: 100%; margin-top: 20px"
          :header-cell-style="{
            backgroundColor: 'rgb(243, 246, 251)',
            fontWeight: 500,
            padding: '6px 0'
          }"
        >
          <el-table-column prop="skuId" label="序号" width="200" type="index" />
          <el-table-column prop="skuName" label="商品名称" width="150" />
          <el-table-column prop="skuImage" label="商品图片" width="150">
            <template #default="{ row }">
              <img
                v-if="row.skuImage"
                :src="row.skuImage"
                alt="图片"
                class="user-avatar"
              >
              <!-- <span v-else class="username">{{
                row.skuName?.substring(0, 1)
              }}</span>
              <span class="name">{{ row.skuName }}</span> -->
            </template>
          </el-table-column>
          <el-table-column prop="brandName" label="品牌" width="180" />
          <el-table-column prop="unit" label="规格" width="170" />
          <el-table-column prop="price" label="商品价格" width="180" />
          <el-table-column prop="className" label="商品类型" width="180">
            <template #default="{ row }">
              <span>{{ row.skuClass.className }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建日期" :formatter="formatDate" width="180" />
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button
                size="mini"
                type="text"
                style="color: #5f84ff; font-size: 15px"
                @click="openDialog('edit', row)"
              >修改</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div v-if="totalPage > 1" class="com_pagination">
        <el-footer>
          <span>共{{ total }}条记录</span>&nbsp;&nbsp;
          <span>第{{ queryObj.pageIndex }}/{{ totalPage }}页</span>
          <el-pagination
            background
            style="float: right"
            :current-page="+queryObj.pageIndex"
            :page-size="+queryObj.pageSize"
            prev-text="上一页"
            next-text="下一页"
            layout="prev, next"
            :total="+total"
            @current-change="handleCurrentChange"
          />
        </el-footer>
      </div>
    </el-card>

    <!-- 新增商品弹窗 -->
    <el-dialog
      :title="drawerTitle"
      :visible.sync="DialogVisible"
      width="35%"
      @close="closeDialog"
    >
      <div class="com_dialog">
        <el-form
          ref="formInline"
          :model="formInline"
          class="demo-form-inline"
          label-width="140px"
          :rules="rules"
        >
          <el-form-item label="商品名称：" prop="skuName">
            <el-input
              v-model="formInline.skuName"
              placeholder="请输入"
              maxlength="15"
              show-word-limit
              type="text"
              style="width: 390px"
            />
          </el-form-item>

          <el-form-item label="品牌：" prop="brandName">
            <el-input
              v-model="formInline.brandName"
              placeholder="请输入"
              maxlength="10"
              show-word-limit
              type="text"
              style="width: 390px"
            />
          </el-form-item>
          <el-form-item label="商品价格（元）：" prop="price" style="width: 390px">
            <el-input-number
              v-model="formInline.price"
              style="width: 390px"
              placeholder="请输入"
              controls-position="right"
              :min="0.5"
              :max="10"
            />
          </el-form-item>
          <el-form-item label="商品类型：" prop="classId">
            <el-select
              v-model="formInline.classId"
              placeholder="请选择"
              style="width: 390px"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.className"
                :value="item.classId"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="规格：" prop="unit">
            <el-input
              v-model="formInline.unit"
              placeholder="请输入"
              maxlength="10"
              show-word-limit
              type="text"
              style="width: 390px"
            />
          </el-form-item>
          <el-form-item label="商品图片：" prop="skuImage">
            <!-- 上传图片 -->
            <UploadImage v-model="formInline.skuImage" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="footer">
          <el-button
            class="com_importData"
            @click="DialogVisible = false"
          >取 消</el-button>
          <el-button
            type="primary"
            class="com_newFile"
            @click="dialogConfirm"
          >确 定</el-button>

        </div>
      </span>
    </el-dialog>

    <!-- 导入数据弹窗 -->
    <el-dialog title="数据导入" :visible.sync="ImportDataVisible" width="450px">
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="标题：">
          <el-upload
            class="upload-demo"
            action="https://jsonplaceholder.typicode.com/posts/"
          >
            <el-button
              size="small"
              type="primary"
              class="btn_upload"
              icon="el-icon-upload"
              style="font-size: 15px"
            >上传文件</el-button>
            <div slot="tip" class="el-upload__tip">
              支持扩展名：xls、xlsx、文件不得大于1M
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <div class="footer">
          <el-button
            class="com_importData"
            @click="ImportDataVisible = false"
          >取 消</el-button>
          <el-button
            type="primary"
            class="com_newFile"
            @click="dataDetermine"
          >确 定</el-button>

        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCommoditys,
  addCommoditys,
  editCommoditys,
  getCommodityList,
  importCommoditys
} from '@/api/goods'
import UploadImage from './components/UploadImage.vue'
export default {
  name: 'CommodityManagement',
  components: { UploadImage },
  data () {
    return {
      formInline: {
        skuName: '',
        brandName: '',
        price: '',
        unit: '',
        skuImage: '',
        classId: ''
      },
      skuId: '',
      form: {},
      tableData: [],
      DialogVisible: false,
      ImportDataVisible: false,
      queryObj: {
        pageIndex: 1,
        pageSize: 10
      },
      total: 0,
      totalCount: 0,
      totalPage: 0,
      type: '',
      skuName: '',
      drawerType: 'add',
      rules: {
        skuName: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        brandName: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        unit: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        className: [
          {
            required: true,
            message: '请输入',
            trigger: 'blur'
          }
        ],
        skuImage: [
          {
            required: true,
            message: '请上传',
            trigger: 'blur'
          }
        ]
      },
      options: []
    }
  },
  computed: {
    drawerTitle () {
      if (this.drawerType === 'add') return '新增商品'
      if (this.drawerType === 'edit') return '修改商品'
      else {
        return 'add'
      }
    }
  },
  created () {
    this.initTable()
    this.getOptions()
    this.onSubmit()
  },
  methods: {
    formatDate (row, column) {
      // 获取单元格数据
      const datac = row[column.property]
      return datac.replace('T', ' ')
    },
    // 查询
    async onSubmit () {
      const data = await getCommoditys({
        skuName: this.skuName,
        ...this.queryObj
      })
      console.log(data)
      this.total = data.total
      this.queryObj.pageIndex = data.pageIndex
      this.queryObj.pageSize = data.pageSize
      this.totalPage = data.totalPage
      this.tableData = data.currentPageRecords
    },

    // 打开弹窗
    async openDialog (type, row) {
      this.drawerType = type
      if (type === 'edit') {
        this.skuId = row.skuId
        this.formInline.skuName = row.skuName
        this.formInline.price = row.price
        this.formInline.unit = row.unit
        this.formInline.brandName = row.brandName
        this.formInline.skuImage = row.skuImage
        this.formInline.classId = row.classId
      }
      this.DialogVisible = true
    },
    // 获取商品类型列表
    async initTable () {
      const data = await getCommoditys(this.queryObj)
      this.tableData = data.currentPageRecords
      this.totalPage = data.totalPage
      this.totalCount = data.totalCount
      // console.log(data)
    },
    // 选择商品类型
    async getOptions () {
      const { currentPageRecords } = await getCommodityList(this.queryObj)
      this.options = currentPageRecords
      // console.log(currentPageRecords)
    },
    // 提交弹窗方法
    async dialogConfirm () {
      try {
        await this.$refs.formInline.validate()
        if (this.drawerType === 'add') {
          await addCommoditys(this.formInline)
        }
        if (this.drawerType === 'edit') {
          await editCommoditys(this.skuId, this.formInline)
        }
        this.DialogVisible = false
        this.closeDialog()
        this.initTable()
        this.$message.success(
          this.drawerType === 'add' ? '添加成功' : '修改成功'
        )
      } catch (error) {
        console.log(error)
      }
    },

    // 关闭弹窗
    closeDialog () {
      // 清空表单
      this.$refs.formInline.resetFields()
      // 关闭弹窗
      this.DialogVisible = false
    },
    // 分页
    handleCurrentChange (val) {
      this.queryObj.pageIndex = val
      this.onSubmit()
    },
    // 导入数据
    importData () {
      this.ImportDataVisible = true
    },
    // 导入数据提交方法
    async dataDetermine () {
      this.$refs.form.validate()
      const data = await importCommoditys()
      console.log(data)
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .el-dialog__body {
  padding: 0;
}
::v-deep .el-dialog {
  border-radius: 10px !important;
}
.footer {
  text-align: center !important;
}
::v-deep .btn-prev:disabled {
  background: #edf0f9 !important;
}
::v-deep .btn-next:disabled {
  background: #edf0f9 !important;
}
::v-deep .btn-prev{
 width: 70px;
 height: 32px;
 background-color: #d5ddf8 !important;
}
::v-deep .btn-next{
  margin: 0 20px;
 width: 70px;
 height: 32px;
 background-color: #d5ddf8 !important;
}
::v-deep .el-table {
 td {
  padding: 8px 0;
  border: none;
 }
 &::before {
  height: 0;
 }
}
.name {
  //  用户名称距离右侧距离
  margin-right: 10px;
  font-size: 16px;
}
.user-avatar {
     display: block;
    width: 24px;
    height: 24px;
    -o-object-fit: cover;
    object-fit: cover;
    border-radius: 50%;
    background: #f3f6fb;
    border: 1px solid #f3f6fb;
}
.username {
  width: 30px;
  height: 30px;
  background-color: #087;
  text-align: center;
  line-height: 30px;
  border-radius: 50%;
  color: #fff;
  margin-right: 10px;
}
.CommodityManagement_header {
  margin: 20px;
}
.com_search {
  margin-left: 10px;
}
.com_input {
  width: 200px;
}
.com_label {
  width: 200px;
}
.com_newFile {
  background: linear-gradient(135deg, #ff9743, #ff5e20) !important;
  border: 0;
}
.btn_search {
  background-color: #5f84ff;
  border: 0;
}
.com_importData {
  background-color: #fbf4f0 !important;
  color: #655b56 !important;
  border: 0;
}
.el-upload__tip {
  font-size: 14px;
  color: #bac0cd;
}
.el-upload__tip1 {
  font-size: 14px;
  color: #bac0cd;
  text-align: center;
}
.btn_upload {
  width: 221px;
  background-color: rgb(95, 132, 255);
  height: 36px;
}
.com_pagination {
  font-size: 16px;
  color: #dbdfe5 !important;
  // float: left;
  padding: 32px 16px;
}
.btn_footer {
  float: right;
  margin-left: 10px;
}
.com_dialog {
  padding: 0px 20px 0px;
  color: #666;
}
</style>
